#include "IFile.h"
#include "stdio.h"
/**
 * @brief
 * <bean interface="IFile" implemation="TextFile">
 *      <path name="temp.txt" readType="w+"/>
 *      <buffer copacity="100" />
 * </bean>
 */
class SimpleFile : public IFile {
public:
    virtual void onLoad(INode *node) {
        init();
        INode *child = node->childNode("path");
        if (child) {
            name = child->getStr("name");
            openType = child->getStr("openType");
        }
        child = node->childNode("buffer");
        if (child) {
            std::string implemation = child->getStr("implemation");
            buffer = (IBuffer*)IPlugin::loadPlugin(implemation.c_str());
            buffer->onLoad(child);
        }
    }
    virtual void onUnload() {
        if (buffer) {
            buffer->onUnload();
        }
    }
    virtual bool init() {
       return false;
    }
    virtual bool start() {
        hF = fopen(name.c_str(),openType.c_str());
        return true;
    }
    virtual bool stop() {
        if (hF) fclose(hF);
        hF = NULL;
        return true;
    }
    virtual bool destroy() {
        return false;
    }
    virtual void bind(IDevice *target) {

    }
    virtual IBuffer *get() {
        int len = fread(buffer->content(),buffer->copacity(),1,hF);
        buffer->resize(len);
        return buffer;
    }
    virtual void put(IBuffer *buf) {
        if (hF)
            fwrite(buf->content(),buf->size(),1,hF);
    }
    SimpleFile() {
        hF = NULL;
        buffer = NULL;
    }
    FILE *hF;
    std::string name;
    IBuffer *buffer;
    std::string openType;
};

REG_PLUGIN(SimpleFile);
